<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\CourseArrangeModel;
use App\Models\CompanyModel;
use App\Models\CourseModel;
use App\Models\StudentCourseModel;
use App\Models\StudentSignModel;

class CalculateCommission extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:calculate-commission';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '计算提成';

    /**
     * 计算每节课的提成，需根据实际上课人数和课程提成方式计算
     */
    public function handle()
    {
        $arrangeCourses = CourseArrangeModel::whereNull('commission')->where('status', 1)->get();
        $courses = [];
        foreach ($arrangeCourses as $agCourse) { 
            $courseId = $agCourse->course_id;
            if(!isset($courses[$courseId])) {
                $courses[$courseId] = CourseModel::find($courseId);
            }

            $course = $courses[$courseId];
            // 学生签到人数
            $studentNum = StudentSignModel::where('arrange_id', $agCourse->id)->whereIn('result', [1,2])->count();
            $commission = 0;
            if ($studentNum > 0) {
                $commission = $this->calculateCommission($studentNum, $course) * $agCourse->course_num;
            }
            $agCourse->commission = $commission;

            // 计算本节课总计销课金额， 需根据学生的购课单价 * 课程数 计算
            $studentSigns = StudentSignModel::where('arrange_id', $agCourse->id)->whereIn('result', [1,2])->get();
            $totalPrice = 0;
            foreach ($studentSigns as $sign) {
                $stuCourse = StudentCourseModel::where([
                        'student_id' => $sign->student_id,
                        'course_id' => $courseId,
                        'pay_status' => 1]
                    )->orderBy('id', 'desc')->first();

                if($stuCourse) {
                    $totalPrice += ($stuCourse->pay_price / ($stuCourse->course_num + $stuCourse->send_num)) * $sign->course_num;
                }
            }
            $agCourse->total_course_money = round($totalPrice, 2);

            $agCourse->save();
        }
    }

    public function calculateCommission($studentNum, CourseModel $course){
        
        if($course->commission_type == 'fixed') { // 固定
            return $course->commission_fixed;
        }
        
        if($course->commission_type == 'num') { // 按课时
            // 学生人数少于基本人数
            if($studentNum <= $course->commission_num_base_num) { 
                return $course->commission_num_base_price;
            }  
            
            // 超出
            $extraCommission = ($studentNum - $course->commission_num_base_num) * $course->commission_num_per;
            return $course->commission_num_base_price + $extraCommission;
        }

        if($course->commission_type == 'stage') { // 阶段性计算
            $stages = json_decode($course->commission_stage, true);
            foreach($stages as $stage) {
                if($studentNum >= $stage['min'] && $studentNum <= $stage['max']) {
                    // 有总提成 优先使用总提成
                    return $stage['total'] > 0 ? $stage['total'] : ($studentNum * $stage['per']);
                }
            }
        }

        return 0;
    }
}
